package com.orangelife.service.propFeeCommInfo.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import com.github.pagehelper.PageHelper;
import com.orangelife.common.MybaitsGenericDaoSubLogic;
import com.orangelife.exception.AppBizException;
import com.orangelife.service.PropFeeType.IPropFeeTypeService;
import com.orangelife.service.cerHouseholder.ICerHouseholderService;
import com.orangelife.service.propFeeApartment.IPropFeeApartmentService;
import com.orangelife.service.propFeeBuilding.IPropFeeBuildingService;
import com.orangelife.service.propFeeComm.IPropFeeCommService;
import com.orangelife.service.propFeeCommInfo.IPropFeeCommInfoService;
import com.orangelife.service.propFeeCommInfo.model.PropFeeCommInfoDto;
import com.orangelife.service.propFeeDic.IPropFeeDicService;
import com.orangelife.service.propFeeUnit.IPropFeeUnitService;
import com.orangelife.setting.constant.CodeConst;
import com.orangelife.setting.constant.InfoConst;
import com.orangelife.setting.constant.TypeConst;
import com.orangelife.utils.DateUtil;
import com.orangelife.utils.HttpSvcUtils;
import com.orangelife.utils.IdUtil;
import com.orangelife.utils.JsonMapUtils;
import com.orangelife.utils.ListSetUtils;
import com.orangelife.utils.ProConfig;
import com.orangelife.utils.StringUtils;
import com.orangelife.utils.UrlPath;

/*****************************************************************
 * Copyright(C) ORANGELIFE Corporation CodeConst.BIS_CODE_68001015. All Rights
 * Reserved.
 *****************************************************************/
/*
 * ============================================================== 功能名
 * PropFeeCommInfo类的 service层的增删改查
 * 
 * @author @author zhr
 * 
 * @version 1.1.0
 * 
 * @date 2016-07-14 11:26:47
 * ==============================================================
 */
@Service("propFeeCommInfoService")
public class PropFeeCommInfoServiceImpl extends MybaitsGenericDaoSubLogic
		implements IPropFeeCommInfoService {
	private static Logger logger = Logger
			.getLogger(PropFeeCommInfoServiceImpl.class);

	public static Logger getLogger() {
		return logger;
	}

	public static void setLogger(Logger logger) {
		PropFeeCommInfoServiceImpl.logger = logger;
	}

	@Resource(name = "propFeeBuildingService")
	private IPropFeeBuildingService propFeeBuildingService;

	@Resource(name = "propFeeUnitService")
	private IPropFeeUnitService propFeeUnitService;
	@Resource(name = "propFeeApartmentService")
	private IPropFeeApartmentService propFeeApartmentService;

	@Resource(name = "propFeeCommService")
	private IPropFeeCommService propFeeCommService;
	@Resource(name = "cerHouseholderService")
	private ICerHouseholderService cerHouseholderService;
	@Resource(name = "propFeeTypeService")
	private IPropFeeTypeService propFeeTypeService;
	@Resource(name = "propFeeDicService")
	private IPropFeeDicService propFeeDicService;

	public IPropFeeBuildingService getPropFeeBuildingService() {
		return propFeeBuildingService;
	}

	public void setPropFeeBuildingService(
			IPropFeeBuildingService propFeeBuildingService) {
		this.propFeeBuildingService = propFeeBuildingService;
	}

	public IPropFeeUnitService getPropFeeUnitService() {
		return propFeeUnitService;
	}

	public void setPropFeeUnitService(IPropFeeUnitService propFeeUnitService) {
		this.propFeeUnitService = propFeeUnitService;
	}

	public IPropFeeApartmentService getPropFeeApartmentService() {
		return propFeeApartmentService;
	}

	public void setPropFeeApartmentService(
			IPropFeeApartmentService propFeeApartmentService) {
		this.propFeeApartmentService = propFeeApartmentService;
	}

	public IPropFeeCommService getPropFeeCommService() {
		return propFeeCommService;
	}

	public void setPropFeeCommService(IPropFeeCommService propFeeCommService) {
		this.propFeeCommService = propFeeCommService;
	}

	@Override
	@Transactional(rollbackFor = { AppBizException.class, Exception.class,
			RuntimeException.class })
	public int addPropFeeCommInfo(PropFeeCommInfoDto propFeeCommInfo)
			throws AppBizException {

		Assert.notNull(propFeeCommInfo);
		/************************************************
		 * 判断输入参数的长度以及是否能为空
		 ************************************************/

		if (!StringUtils.isBlank(propFeeCommInfo.getCode())) {
			if (propFeeCommInfo.getCode().length() > 32) {
				throw new AppBizException(CodeConst.SYS_CODE_1002, "信息编码长度超出");
			}
		}

		if (!StringUtils.isBlank(propFeeCommInfo.getName())) {
			if (propFeeCommInfo.getName().length() > 64) {
				throw new AppBizException(CodeConst.SYS_CODE_1002, "信息名称长度超出");
			}
		}

		if (!StringUtils.isBlank(propFeeCommInfo.getVal())) {
			if (propFeeCommInfo.getVal().length() > 36) {
				throw new AppBizException(CodeConst.SYS_CODE_1002, "信息值长度超出");
			}
		}

		List<PropFeeCommInfoDto> feeCommInfoDtos = this
				.findPropFeeCommInfoByRelevantID(null,
						propFeeCommInfo.getCommID(), propFeeCommInfo.getCode(),
						null, propFeeCommInfo.getVal(),
						propFeeCommInfo.getType());
		if (feeCommInfoDtos != null && feeCommInfoDtos.size() > 0) {
			throw new AppBizException(2, "亲该信息已经存在");

		}

		propFeeCommInfo.setInfoID(IdUtil.getuuId());
		propFeeCommInfo.setItemStat(TypeConst.FLAG_ON);
		propFeeCommInfo.setTscreate(new Date());
		propFeeCommInfo.setTsedit(new Date());
		return this.getSqlSession().insert(
				"PropFeeCommInfoMapper.insertSelective", propFeeCommInfo);
	}

	@Override
	@Transactional(rollbackFor = { AppBizException.class, Exception.class,
			RuntimeException.class })
	public int editPropFeeCommInfo(PropFeeCommInfoDto propFeeCommInfo)
			throws AppBizException {

		Assert.notNull(propFeeCommInfo);
		/************************************************
		 * 判断输入参数的长度以及是否能为空
		 ************************************************/
		if (StringUtils.isBlank(propFeeCommInfo.getInfoID())) {
			throw new AppBizException(CodeConst.SYS_CODE_1001, "ID不可为空");
		}
		PropFeeCommInfoDto oldPropFeeCommInfo = this
				.findPropFeeCommInfoByID(propFeeCommInfo.getInfoID());

		if (!StringUtils.isBlank(propFeeCommInfo.getCode())) {
			if (propFeeCommInfo.getCode().length() > 32) {
				throw new AppBizException(CodeConst.SYS_CODE_1002,
						"信息编码(fixdate:固定费用已生成时间，pubdate公摊费用已生成时间)长度超出");
			}
		}

		if (!StringUtils.isBlank(propFeeCommInfo.getName())) {
			if (propFeeCommInfo.getName().length() > 64) {
				throw new AppBizException(CodeConst.SYS_CODE_1002, "信息名称长度超出");
			}
		}

		if (!StringUtils.isBlank(propFeeCommInfo.getVal())) {
			if (propFeeCommInfo.getVal().length() > 36) {
				throw new AppBizException(CodeConst.SYS_CODE_1002, "信息值长度超出");
			}
		}

		if (oldPropFeeCommInfo == null) {
			throw new AppBizException(CodeConst.BIS_CODE_68001,
					InfoConst.BIS_INFO_68001);
		}
		// List<PropFeeCommInfoDto> feeCommInfoDtos = this
		// .findPropFeeCommInfoByRelevantID(null,
		// propFeeCommInfo.getCommID(), propFeeCommInfo.getCode(),
		// null, propFeeCommInfo.getVal(),
		// propFeeCommInfo.getType());
		// if (feeCommInfoDtos != null && feeCommInfoDtos.size() > 1) {
		// throw new AppBizException(2, "亲该信息已经存在");
		//
		// }
		propFeeCommInfo.setTsedit(new Date());
		return this.getSqlSession().update(
				"PropFeeCommInfoMapper.updateByPrimaryKeySelective",
				propFeeCommInfo);
	}

	@Override
	public PropFeeCommInfoDto findPropFeeCommInfoByID(String propFeeCommInfoID)
			throws AppBizException {
		if (StringUtils.isBlank(propFeeCommInfoID)) {

			throw new AppBizException(CodeConst.SYS_CODE_1001, "ID不可为空");
		}

		/************************************************
		 * 判断实体是否存在
		 ************************************************/
		PropFeeCommInfoDto oldPropFeeCommInfo = this.getSqlSession().selectOne(
				"PropFeeCommInfoSearchMapper.selectByPrimaryKey",
				propFeeCommInfoID);
		if (oldPropFeeCommInfo == null) {
			throw new AppBizException(CodeConst.BIS_CODE_68001,
					InfoConst.BIS_INFO_68001);
		}

		if (TypeConst.FLAG_OFF.equals(oldPropFeeCommInfo.getItemStat())) {

			throw new AppBizException(CodeConst.BIS_CODE_68001,
					InfoConst.BIS_INFO_68001);
		}
		return oldPropFeeCommInfo;
	}

	@Override
	@Transactional(rollbackFor = { AppBizException.class, Exception.class,
			RuntimeException.class })
	public int deletePropFeeCommInfoByLogic(String propFeeCommInfoID)
			throws AppBizException {

		if (StringUtils.isBlank(propFeeCommInfoID)) {
			throw new AppBizException(CodeConst.SYS_CODE_1001, "ID不可为空");
		}
		/************************************************
		 * 判断实体是否存在
		 ************************************************/
		PropFeeCommInfoDto oldPropFeeCommInfo = this
				.findPropFeeCommInfoByID(propFeeCommInfoID);

		oldPropFeeCommInfo.setItemStat(TypeConst.FLAG_OFF);
		oldPropFeeCommInfo.setTsedit(new Date());
		return this.getSqlSession().update(
				"PropFeeCommInfoMapper.updateByPrimaryKeySelective",
				oldPropFeeCommInfo);
	}

	@Override
	public List<Map<String, Object>> findPropFeeCommInfoByPage(String type,
			String commID, String tsCreate, String search, int pageNo,
			int pageSize) throws AppBizException {

		/************************************************
		 * 设置输入参数
		 ************************************************/
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("tsCreate", tsCreate);
		map.put("commID", commID);
		map.put("type", type);
		map.put("search", search);

		/*
		 * if (!StringUtils.isBlank(search)) { Map<String, Object> pam = new
		 * HashMap<String, Object>();
		 * 
		 * pam.put("search", search); List<Map<String, Object>> comms =
		 * JsonMapUtils
		 * .getPageEntityMap(HttpSvcUtils.doGetSvc(UrlPath.searComm, pam,
		 * null)); List<String> commIDs = new ArrayList<String>();
		 * commIDs.add("-1"); for (Map<String, Object> comm : comms) {
		 * commIDs.add(comm.get("commID").toString());
		 * 
		 * } map.put("commIDs", commIDs); map.put("search", search);
		 * 
		 * }
		 */
		PageHelper.startPage(pageNo, pageSize);
		List<Map<String, Object>> list = this.getSqlSession().selectList(
				"PropFeeCommInfoSearchMapper.findAllPropFeeCommInfo", map);

		/*
		 * if (list != null && list.size() > 0) {
		 * 
		 * List<String> commIDs = new ArrayList<String>(); for (Map<String,
		 * Object> open : list) { commIDs.add(open.get("comm_id").toString()); }
		 * List<Map<String, Object>> comms = JsonMapUtils
		 * .getPageEntityMap(HttpSvcUtils.doPostSvc(UrlPath.bauthComm, commIDs,
		 * null)); Map<String, String> connValue = new HashMap<String,
		 * String>(); connValue.put("comm", "comm"); list =
		 * SplicingUtils.connoList(list, comms, "comm_id", "commID", connValue);
		 * }
		 */
		return list;
	}

	@Override
	public List<PropFeeCommInfoDto> getPropFeeCommInfoByPage(String tsCreate,
			String search, int pageNo, int pageSize) throws AppBizException {
		/************************************************
		 * 设置输入参数
		 ************************************************/
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("tsCreate", tsCreate);
		map.put("search", search);
		PageHelper.startPage(pageNo, pageSize);
		List<PropFeeCommInfoDto> list = this.getSqlSession().selectList(
				"PropFeeCommInfoSearchMapper.getAllPropFeeCommInfoDto", map);
		return list;
	}

	@Override
	public List<Map<String, Object>> selectPropFeeCommInfoByRelevantID(
			String infoID, String commID) throws AppBizException {
		/************************************************
		 * 设置输入参数
		 ************************************************/
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("infoID", infoID);
		map.put("commID", commID);

		List<Map<String, Object>> list = this
				.getSqlSession()
				.selectList(
						"PropFeeCommInfoSearchMapper.selectPropFeeCommInfoDtoyRelevantID",
						map);
		return list;
	}

	@Override
	public List<PropFeeCommInfoDto> findPropFeeCommInfoByRelevantID(
			String infoID, String commID, String code, String name, String val,
			String type) throws AppBizException {
		/************************************************
		 * 设置输入参数
		 ************************************************/
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("infoID", infoID);
		map.put("commID", commID);
		map.put("name", name);
		map.put("code", code);
		map.put("val", val);
		map.put("type", type);
		List<PropFeeCommInfoDto> list = this
				.getSqlSession()
				.selectList(
						"PropFeeCommInfoSearchMapper.findPropFeeCommInfoDtoByRelevantID",
						map);
		return list;
	}

	@Override
	public List<PropFeeCommInfoDto> bauthfindPropFeeCommInfo(
			List<String> propFeeCommInfoIDs) throws AppBizException {
		/************************************************
		 * 设置输入参数
		 ************************************************/
		List<PropFeeCommInfoDto> list = this.getSqlSession().selectList(
				"PropFeeCommInfoSearchMapper.batchFindPropFeeCommInfo",
				propFeeCommInfoIDs);
		return list;
	}

	@Override
	public List<Map<String, Object>> bauthfindPropFeeCommInfoByMap(
			Map<String, Object> propFeeCommInfo) throws AppBizException {
		/************************************************
		 * 设置输入参数
		 ************************************************/
		List<Map<String, Object>> list = this.getSqlSession().selectList(
				"PropFeeCommInfoSearchMapper.batchFindPropFeeCommInfoByMap",
				propFeeCommInfo);
		return list;
	}

	@Override
	public void clearCache() throws AppBizException {
		System.out.println("清除缓存成功");
	}

	@Override
	public List<Map<String, Object>> findPropFeeCommInfo(Map<String, Object> map)
			throws AppBizException {
		List<Map<String, Object>> list = this.getSqlSession().selectList(
				"PropFeeCommInfoSearchMapper.findAllPropFeeCommInfos", map);
		return list;
	}

	@Override
	@Transactional(rollbackFor = { AppBizException.class, Exception.class,
			RuntimeException.class })
	public int addPropFeeCommInfo(List<PropFeeCommInfoDto> propFeeCommInfos)
			throws AppBizException {

		boolean isAdd = false;
		for (PropFeeCommInfoDto propFeeCommInfo : propFeeCommInfos) {
			if (StringUtils.isBlank(propFeeCommInfo.getCommID())) {
				throw new AppBizException(2, "亲，小区信息");
			}
			if (!StringUtils.isBlank(propFeeCommInfo.getInfoID())) {
				this.editPropFeeCommInfo(propFeeCommInfo);
			} else {
				isAdd = true;
			}
		}
		if (isAdd == true) {

			for (PropFeeCommInfoDto propFeeCommInfo : propFeeCommInfos) {
				propFeeCommInfo.setInfoID(IdUtil.getuuId());
				propFeeCommInfo.setItemStat(TypeConst.FLAG_ON);
				propFeeCommInfo.setTscreate(new Date());
				propFeeCommInfo.setTsedit(new Date());
			}

			return this.getSqlSession().insert(
					"PropFeeCommInfoBauthMapper.bauthInsert", propFeeCommInfos);

		}

		return 1;
	}

	@Override
	public Map<String, Map<String, Object>> findPropFeeCommInfo(String commID)
			throws AppBizException {

		Map<String, Object> map = new HashMap<String, Object>();

		map.put("commID", commID);

		Map<String, Map<String, Object>> p = this.getSqlSession().selectMap(
				"PropFeeCommInfoSearchMapper.batchFindPropFeeCommInfoByMap",
				map, "code");
		// TODO Auto-generated method stub
		return p;
	}

	@Override
	public String findValByCode(String commID, String code)
			throws AppBizException {
		Map<String, Object> map = new HashMap<String, Object>();

		map.put("commID", commID);
		map.put("code", code);
		List<Map<String, Object>> list = this
				.bauthfindPropFeeCommInfoByMap(map);

		if (list == null || list.size() == 0 || list.size() > 1) {

			return null;
		}

		map = list.get(0);
		if (map == null || map.get("val") == null) {

			return null;
		}

		// TODO Auto-generated method stub
		return StringUtils.toString(map.get("val"));
	}

	@Override
	public Map<String, String> findLastDate(String commID)
			throws AppBizException {

		Map<String, Map<String, Object>> config = this
				.findPropFeeCommInfo(commID);

		if (config == null
				|| config.get("curDate") == null
				|| StringUtils.isBlank(config.get("curDate").get("val")
						.toString())
				|| config.get("period") == null
				|| StringUtils.isBlank(config.get("period").get("val")
						.toString())) {

			// BillService.setFeeStatusUnlock(commID);
			return null;

		}
		String startTime = config.get("curDate").get("val").toString();

		String endTime = "";
		if ("1".equals(config.get("period").get("val").toString())) {

			endTime = DateUtil.addMonth(startTime, 1);

		} else if ("2".equals(config.get("period").get("val").toString())) {

			endTime = DateUtil.getNextQuarter(startTime);

		}
		Map<String, String> m = new HashMap<String, String>();
		m.put("lastTime", startTime);
		m.put("period", config.get("period").get("val").toString());
		m.put("nextTime", endTime);

		// TODO Auto-generated method stub
		return m;
	}

	@Override
	@Transactional(rollbackFor = { AppBizException.class, Exception.class,
			RuntimeException.class })
	public synchronized void synchrodata(String commID) throws AppBizException {
		List<String> commIDs = new ArrayList<String>();
		commIDs.add(commID);
		List<Map<String, Object>> comm = JsonMapUtils
				.getPageEntityMap(HttpSvcUtils.doPostSvc(UrlPath.bauthComm,
						commIDs, null));
		if (comm == null || comm.size() <= 0) {
			throw new AppBizException(2, "亲，小区信息同步失败");
		}

		ListSetUtils listSetUtils = new ListSetUtils();

		/***
		 * 添加小区
		 */
		HandleCommThread commthread = new HandleCommThread("小区线程[] ", comm,
				propFeeCommService);
		commthread.start();

		/***
		 * 添加楼栋
		 */

		List<Map<String, Object>> builds = JsonMapUtils
				.getPageEntityMap(HttpSvcUtils.doGetSvc(
						UrlPath.conurl(UrlPath.getBuilds, commID, null), null));
		List<List<Map<String, Object>>> buildings = listSetUtils.splitList(
				builds, 100);

		for (int i = 0; i < buildings.size(); i++) {
			HandleBuildingThread thread = new HandleBuildingThread("楼栋线程["
					+ (i) + "] ", buildings.get(i), propFeeBuildingService);
			thread.start();
		}

		/***
		 * 添加单元
		 */
		List<Map<String, Object>> units = JsonMapUtils
				.getPageEntityMap(HttpSvcUtils.doGetSvc(UrlPath.getUnits
						+ "?commID=" + commID, null));
		List<List<Map<String, Object>>> unit = listSetUtils.splitList(units,
				100);

		for (int i = 0; i < unit.size(); i++) {
			HandleUnitThread thread = new HandleUnitThread(
					"单元线程[" + (i) + "] ", unit.get(i), propFeeUnitService);
			thread.start();
		}

		/***
		 * 添加房屋
		 */

		List<Map<String, Object>> apartments = JsonMapUtils
				.getPageEntityMap(HttpSvcUtils.doGetSvc(UrlPath.getApaprtMents
						+ "?commID=" + commID, null));

		List<List<Map<String, Object>>> apartmentInfo = listSetUtils.splitList(
				apartments, 100);

		for (int i = 0; i < apartmentInfo.size(); i++) {
			HandleApartmentsThread thread = new HandleApartmentsThread("房屋线程["
					+ (i) + "] ", apartmentInfo.get(i), propFeeApartmentService);
			thread.start();
		}

		/***
		 * 添加 业主
		 */

		List<Map<String, Object>> owners = JsonMapUtils
				.getPageEntityMap(HttpSvcUtils.doGetSvc(UrlPath.getOwners
						+ "?type=0&commID=" + commID, null));
		List<List<Map<String, Object>>> owner = listSetUtils.splitList(owners,
				100);

		for (int i = 0; i < owner.size(); i++) {
			HandleCerHouseholderThread thread = new HandleCerHouseholderThread(
					"业主线程[" + (i) + "] ", commID, owner.get(i),
					cerHouseholderService);
			thread.start();
		}

		/***
		 * 更新删除信息
		 */
		Map<String, Object> hasDeleteInfo = JsonMapUtils
				.getEntityMaps(HttpSvcUtils.doGetSvc(UrlPath.hasDeletePropInfo
						+ "?commID=" + commID, null));
		HandleDeletedInfoThread handleDeletedInfoThread = new HandleDeletedInfoThread(
				"更新删除信息线程", hasDeleteInfo, propFeeCommService,
				propFeeBuildingService, propFeeUnitService,
				propFeeApartmentService, cerHouseholderService);
		handleDeletedInfoThread.start();
		/****
		 * 初始化表类型
		 */
		String feeTypes[] = ProConfig.getProValues("INIT_FEETYPE").toString()
				.split(",");
		List<String> feeTypeNames = new ArrayList<String>(
				Arrays.asList(feeTypes));
		HandleFeeTypeThread feeTypeThread = new HandleFeeTypeThread("表线程",
				feeTypeNames, commID, propFeeTypeService, propFeeDicService);
		feeTypeThread.start();

	}
}
